from flask import g, Blueprint, request, jsonify, render_template, redirect

from common import Result
from forms import AddStudentForm
from models import User, Root, Teacher, Student, Classes, TestPaper, StudentClassesRel, SingleChoiceQuestionBank, \
    ShortAnswerQuestionBank, JudgmentalQuestionBank, PictureQuestionBank, SignIn
from exts import db, get_time
from flask_login import login_required
from decorations import root_required

bp = Blueprint("admin", __name__, url_prefix="/admin")


# todo before_request
@bp.before_request
@login_required
@root_required
def before_request():
    pass


# todo /query_sign_in_table
@bp.route("/query_sign_in_table", methods=["GET"])
def query_sign_in_table():
    id_classes = request.values.get("id_classes")
    data = {
        "code": 0,
        "msg": "",
        "count": 0,
        "data": []
    }
    for i in db.session.query(StudentClassesRel).filter(StudentClassesRel.id_classes == id_classes).all():
        data["data"].append({
            "id": i.student.id,
            "name": i.student.name,
            "phone": i.student.phone,
            "parent_phone": i.student.parent_phone,
            "sign_in_count": len(db.session.query(SignIn).filter(SignIn.id_student == i.student.id).all())
        })

    return jsonify(data)


# todo /add_student
@bp.route("/add_student", methods=["POST"])
def add_student():
    asf = AddStudentForm(request.form)
    if not asf.validate():
        return Result.error(
            msg=str(asf.errors)
        )

    db.session.query(User).filter(
        User.username == asf.username.data
    )

    # print(username, password, power, name, phone)

    user = User(
        username=asf.username.data,
        password=asf.password.data,
        power=2,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
    )

    student = Student(
        parent_phone=asf.parent_phone.data,
        age=asf.age.data,
        material_cost=asf.material_cost.data,
        name=asf.name.data,
        phone=asf.phone.data,
        user=user
    )

    scr = StudentClassesRel(
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        student=student,
        classes=db.session.query(Classes).get(asf.id_classes.data)
    )

    db.session.add(student)
    db.session.add(scr)
    db.session.commit()

    # redirect("/admin/add_student_url")
    return Result.success(
        msg='添加成功'
    )


# todo /add_teacher
@bp.route("/add_teacher", methods=["POST"])
def add_teacher():
    username = request.values.get("username")
    password = request.values.get("password")
    name = request.values.get("name")
    phone = request.values.get("phone")

    print(username, password, name, phone)

    user = User(
        username=username,
        password=password,
        power=1,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0
    )

    teacher = Teacher(
        name=name,
        phone=phone,
        user=user
    )

    db.session.add(teacher)
    db.session.commit()

    return redirect("/admin/add_teacher_url")


# todo /add_root
@bp.route("/add_root", methods=["POST"])
def add_root():
    username = request.values.get("username")
    password = request.values.get("password")
    name = request.values.get("name")
    phone = request.values.get("phone")

    # print(username, password, power, name, phone)

    user = User(
        username=username,
        password=password,
        power=0,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
    )

    root = Root(
        name=name,
        phone=phone,
        user=user
    )

    db.session.add(root)
    db.session.commit()

    return redirect("/admin/add_root_url")


# todo /query_class
@bp.route("/query_class")
def query_class():
    page = request.values.get("page")
    limit = request.values.get("limit")
    paginate = db.session.query(Classes).paginate(page=int(page), per_page=int(limit))

    data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(Classes).all()),
        "data": []
    }

    for i in paginate.items:
        data["data"].append({
            "id": i.id,
            "name": i.name,
            "student_number": len(i.student_classes_rel),
            "room": i.room,
            "time": i.time,
            "teacher": i.teacher.name
        })

    return jsonify(data)


# todo /query_student
@bp.route("/query_student")
def query_student():
    page = request.values.get("page")
    limit = request.values.get("limit")
    paginate = db.session.query(User).filter(User.power == 2).paginate(page=int(page), per_page=int(limit))
    # print(paginate.items)

    return_data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(User).filter(User.power == 2).all()),
        "data": []
    }
    for user in paginate.items:
        data = {
            "id": user.id,
            "username": user.username,
            'password': user.password,
            'power': user.power,
            'create_time': user.create_time,
            'update_time': user.update_time,
            'is_delete': user.is_delete
        }

        if user.power == 0:
            data["name"] = user.root.name
        elif user.power == 1:
            data["name"] = user.teacher.name
            data["phone"] = user.teacher.phone
        else:
            data["name"] = user.student.name
            data["phone"] = user.student.phone

        return_data["data"].append(data)

    return jsonify(return_data)


# todo /query_teacher
@bp.route("/query_teacher")
def query_teacher():
    page = request.values.get("page")
    limit = request.values.get("limit")
    paginate = db.session.query(User).filter(User.power == 1).paginate(page=int(page), per_page=int(limit))
    # print(paginate.items)

    return_data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(User).filter(User.power == 1).all()),
        "data": []
    }
    for user in paginate.items:
        data = {
            "username": user.username,
            'password': user.password,
            'power': user.power,
            'create_time': user.create_time,
            'update_time': user.update_time,
            'is_delete': user.is_delete
        }

        if user.power == 0:
            data["name"] = user.root.name
        elif user.power == 1:
            data["name"] = user.teacher.name
            data["phone"] = user.teacher.phone
        else:
            data["name"] = user.student.name
            data["phone"] = user.student.phone

        return_data["data"].append(data)

    return jsonify(return_data)


# todo /query_root
@bp.route("/query_root")
def query_root():
    page = request.values.get("page")
    limit = request.values.get("limit")
    paginate = db.session.query(User).filter(User.power == 0).paginate(page=int(page), per_page=int(limit))
    # print(paginate.items)

    return_data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(User).filter(User.power == 0).all()),
        "data": []
    }
    for user in paginate.items:
        data = {
            "username": user.username,
            'password': user.password,
            'power': user.power,
            'create_time': user.create_time,
            'update_time': user.update_time,
            'is_delete': user.is_delete
        }

        if user.power == 0:
            data["name"] = user.root.name
        elif user.power == 1:
            data["name"] = user.teacher.name
            data["phone"] = user.teacher.phone
        else:
            data["name"] = user.student.name
            data["phone"] = user.student.phone

        return_data["data"].append(data)

    return jsonify(return_data)


# todo /query_test_paper
@bp.route("/query_test_paper", methods=["POST", "GET"])
def query_test_paper():
    page = request.values.get("page")
    limit = request.values.get("limit")
    paginate = db.session.query(TestPaper).paginate(page=int(page), per_page=int(limit))
    # print(paginate.items)
    # test_paper = db.session.query(TestPaper).all()
    data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(TestPaper).all()),
        "data": []
    }
    for i in paginate.items:
        if i.state == 0:
            state = "制作中"
        elif i.state == 1:
            state = "已发布"
        else:
            state = "已收卷"

        data["data"].append({
            "id": i.id,
            "name": i.name,
            "state": state,
            "author": i.teacher.name,
            "create_time": i.create_time
        })

    return jsonify(data)


# todo url /student_list
@bp.route("/student_list")
def student_list():
    content = {
        "user": g.user,
    }
    return render_template("admin/student_list.html", **content)


# todo url /teacher_list
@bp.route("/teacher_list")
def teacher_list():
    content = {
        "user": g.user,
    }
    return render_template("admin/teacher_list.html", **content)


# todo url /root_list
@bp.route("/root_list")
def root_list():
    content = {
        "user": g.user,
    }
    return render_template("admin/root_list.html", **content)


# todo url /add_student_url
@bp.route("/add_student_url")
def add_student_url():
    content = {
        "user": g.user,
        "classes": db.session.query(Classes).all()
    }
    return render_template("admin/add_student.html", **content)


# todo url /add_teacher_url
@bp.route("/add_teacher_url")
def add_teacher_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/add_teacher.html", **content)


# todo url /add_root_url
@bp.route("/add_root_url")
def add_root_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/add_root.html", **content)


# todo url /add_classes_url
@bp.route("/add_classes_url")
def add_classes_url():
    content = {
        "user": g.user,
        "teacher": db.session.query(Teacher).all()
    }
    return render_template("admin/add_classes.html", **content)


# todo url /class_list
@bp.route("/class_list")
def class_list():
    content = {
        "user": g.user,
    }
    return render_template("admin/class_list.html", **content)


# todo url /test_paper_list_url
@bp.route("/test_paper_list_url")
def test_paper_list_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/test_paper_list.html", **content)


# todo url /view_a_class_url
@bp.route("/view_a_class_url")
def view_a_class_url():
    id_classes = request.values.get("id_classes")
    classes = db.session.query(Classes).get(id_classes)
    student_classes_rel = db.session.query(StudentClassesRel).filter(StudentClassesRel.id_classes == id_classes).all()

    content = {
        "user": g.user,
        "student_classes_rel": student_classes_rel,
        "classes": classes,
    }
    return render_template("admin/view_a_class.html", **content)


# todo url /question_bank_list_url 查看题库
@bp.route("/question_bank_list_url")
def question_bank_list_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/question_bank_list.html", **content)


# todo url /add_question_bank_url 添加题库
@bp.route("/add_question_bank_url")
def add_question_bank_url():
    id_question_bank = request.values.get("id_question_bank")
    content = {
        "user": g.user,
        "id_question_bank": id_question_bank
    }
    return render_template("admin/add_question_bank.html", **content)


# todo url /questions_list_url 查看某个题库里面的题目
@bp.route("/questions_list_url")
def questions_list_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/questions_list.html", **content)


# todo url /add_questions_url 添加题目到某个题库
@bp.route("/add_questions_url")
def add_questions_url():
    id_question_bank = request.values.get("id_question_bank")
    single_choice = db.session.query(SingleChoiceQuestionBank).filter(SingleChoiceQuestionBank.id_question_bank == id_question_bank).all()
    judgmental = db.session.query(JudgmentalQuestionBank).filter(JudgmentalQuestionBank.id_question_bank == id_question_bank).all()
    short_answer = db.session.query(ShortAnswerQuestionBank).filter(ShortAnswerQuestionBank.id_question_bank == id_question_bank).all()
    picture_question = db.session.query(PictureQuestionBank).filter(PictureQuestionBank.id_question_bank == id_question_bank).all()
    content = {
        "user": g.user,
        "single_choice": single_choice,
        "judgmental": judgmental,
        "short_answer": short_answer,
        "id_question_bank": id_question_bank,
        "picture_question": picture_question
    }
    return render_template("admin/add_questions.html", **content)


# todo url /add_questions_from_table_url 从表格中导入题目到某个题库
@bp.route("/add_questions_from_table_url")
def add_questions_from_table_url():
    id_question_bank = request.values.get("id_question_bank")
    single_choice = db.session.query(SingleChoiceQuestionBank).filter(SingleChoiceQuestionBank.id_question_bank == id_question_bank).all()
    judgmental = db.session.query(JudgmentalQuestionBank).filter(JudgmentalQuestionBank.id_question_bank == id_question_bank).all()
    short_answer = db.session.query(ShortAnswerQuestionBank).filter(ShortAnswerQuestionBank.id_question_bank == id_question_bank).all()
    picture_question = db.session.query(PictureQuestionBank).filter(PictureQuestionBank.id_question_bank == id_question_bank).all()
    content = {
        "user": g.user,
        "single_choice": single_choice,
        "judgmental": judgmental,
        "short_answer": short_answer,
        "id_question_bank": id_question_bank,
        "picture_question": picture_question
    }
    return render_template("admin/add_questions_from_table.html", **content)


# todo url /query_teacher_question_bank_rel_url 权限管理: 查看所有题库列表，标记持有人数(teacher)
@bp.route("/query_teacher_question_bank_rel_url")
def query_teacher_question_bank_rel_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/teacher_question_bank_rel.html", **content)


# todo url /query_question_bank_holder_url 查看某个题库的持有者详情
@bp.route("/query_question_bank_holder_url")
def query_question_bank_holder_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/query_question_bank_holder.html", **content)


# todo url /sign_in_log_classes_url 管理员查看班级签到
@bp.route("/sign_in_log_classes_url")
def sign_in_log_classes_url():
    content = {
        "user": g.user,
        "classes": db.session.query(Classes).all()
    }
    return render_template("admin/sign_in_log_classes.html", **content)


# todo url /sign_in_log_table_url
@bp.route("/sign_in_log_table_url")
def sign_in_log_table_url():
    content = {
        "user": g.user,
    }
    return render_template("admin/sign_in_log_table.html", **content)


# todo url /see_a_student_sign_in_url
@bp.route("/see_a_student_sign_in_url")
def see_a_student_sign_in_url():
    id_student = request.values.get("id_student")
    content = {
        "user": g.user,
        "sign_up": db.session.query(SignIn).filter(SignIn.id_student == id_student).all()
    }
    return render_template("admin/see_a_student_sign_in.html", **content)
